package com.example.bookmall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bookmall.entity.*;
import com.example.bookmall.entity.address.Address;
import com.example.bookmall.entity.address.AddressVo;
import com.example.bookmall.entity.order.*;
import com.example.bookmall.entity.usercore.User;
import com.example.bookmall.mapper.AftersalesMapper;
import com.example.bookmall.mapper.BookMapper;
import com.example.bookmall.mapper.OrderItemMapper;
import com.example.bookmall.mapper.OrderMapper;
import com.example.bookmall.service.*;
import com.example.bookmall.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

//TODO：购买的时候要考虑库存
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private CartService cartService;
    @Autowired
    private BookService bookService;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private AftersalesMapper aftersalesMapper;
    @Autowired
    private AftersalesService aftersalesService;

    //创建订单  无论都要支付 默认1
    @Override
    @Transactional public Result createOrder(OrderSubmitDto orderSubmitDto) {
        // 1. 校验购物车ID列表是否为空
        List<Integer> cartIds = orderSubmitDto.getCartIds();
        if (cartIds == null || cartIds.isEmpty()) {
            return Result.error( "购物车不能为空");
        }



        // 2. 生成唯一订单号
        String orderId = generateOrderId();

        // 3. 获取购物车商品并检查是否存在或下架
        List<Cart> cartItems = cartService.listByIds(cartIds);
        if (cartItems == null || cartItems.isEmpty()) {
            return Result.error( "购物车商品不存在或已下架");
        }

        if(orderSubmitDto.getAddressId()== null){
            return Result.error( "请选择收货地址");
        }

        // 检查每本商品是否下架
        for (Cart cartItem : cartItems) {
            Book book = bookService.getById(cartItem.getBookId());
            if (book == null || book.getStatus() == 0) { // 假设0表示下架状态
                return Result.error( "商品已下架");
            }
            if(book.getStock() < cartItem.getQuantity()){
                return Result.error( "库存不足");
            }
            bookService.decreaseStock(book.getBookId(),cartItem.getQuantity());
        }


        // 4. 计算订单总金额
        BigDecimal totalAmount = calculateTotalAmount(cartItems);

        // 5. 获取当前用户
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");

        // 6. 创建订单主表记录
        Orders order = new Orders();
        order.setOrderId(orderId);
        order.setUserId(userId);
        order.setAddressId(orderSubmitDto.getAddressId());
        order.setTotalAmount(totalAmount);
        order.setOrderStatus(orderSubmitDto.getOrderStatus()); // 是否支付
        order.setPayMethod(orderSubmitDto.getPayMethod());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        save(order);

        // 7. 创建订单明细
        for (Cart cartItem : cartItems) {
            Book book = bookService.getById(cartItem.getBookId());

            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orderId);
            orderItem.setBookId(book.getBookId());
            orderItem.setBooktitle(book.getTitle());
            orderItem.setBookcover(book.getCoverUrl());
            orderItem.setPrice(book.getPrice());
            orderItem.setQuantity(cartItem.getQuantity());

            orderItemMapper.insert(orderItem);
        }

        // 8. 删除购物车中的商品
        cartService.removeByIds(orderSubmitDto.getCartIds(), userId);

        return Result.success(orderId);
    }

    @Override
    public Result<PageResultVO<OrderVo>> getAllOrder(Integer pageNum, Integer pageSize, String keyword, Integer status) {
        return null;
    }

    //支付订单 把状态设置成2
    @Override
    @Transactional
    public boolean payOrder(String orderId) {
        // 模拟支付过程
        Orders order = orderMapper.selectById(orderId);
        if (order == null || order.getOrderStatus() != 0) {
            return false;
        }

        // 更新订单状态为已支付
        order.setOrderStatus(2);
        order.setPayTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        int affectedRows = orderMapper.updateById(order);

        return affectedRows>0?true:false;
    }

    //取消订单
    @Override
    @Transactional
    public boolean cancelOrder(String orderId) {

        Orders order = orderMapper.selectById(orderId);

        if (order == null || order.getOrderStatus() != 0) {
            return false;
        }

        //校验订单状态（只允许取消未支付或未发货或待收货的订单）
        if (!OrderStatus.PENDING_PAYMENT.getCode().equals(order.getOrderStatus())&&
                !OrderStatus.PENDING_SHIPMENT.getCode().equals(order.getOrderStatus())&&
                !OrderStatus.PENDING_RECEIPT.getCode().equals(order.getOrderStatus())) {
            log.error("订单状态不允许取消");
            //TODO：这里抛出一个异常，提示用户订单状态不允许取消 不知道如何抛出异常
            throw new RuntimeException("订单状态不允许取消");
        }
        // 更新订单状态为已取消
        order.setOrderStatus(5);
        order.setUpdateTime(LocalDateTime.now());

        int affectedRows = orderMapper.updateById(order);

        return affectedRows>0?true:false;
    }


    //获取订单详情 根据订单id
    @Override
    public OrderVo getOrderDetail(String orderId) {
        // 1. 查询订单基本信息
        Orders order = getById(orderId);
        if (order == null) {
            return null;
        }

        // 2. 组装OrderVo基本信息
        OrderVo orderVo = new OrderVo();
        BeanUtils.copyProperties(order, orderVo); // 复制基本属性

        // 3. 查询用户信息
        User user = userService.findById(order.getUserId());

        if (user != null) {
            orderVo.setUsername(user.getUsername());
        }

        // 4. 查询收货地址信息 (假设存在Address表)
        Address address = addressService.getByIdIncludeDeleted(order.getAddressId());

        AddressVo addressVo = new AddressVo();

        if (address != null) {
            BeanUtils.copyProperties(address, addressVo);
        }
        if (address != null) {
            orderVo.setAddressVo(addressVo);
            orderVo.setConsignee(address.getConsignee());
            orderVo.setPhone(address.getPhone());
            orderVo.setDatetime(order.getCreateTime()); // 设置下单时间

        }


        Aftersales aftersales = aftersalesService.findByOrderId(orderId);
        if(aftersales!=null){
            orderVo.setReason(aftersales.getReason());
            orderVo.setAdminReason(aftersales.getAdminReason());
            orderVo.setAdminAgreement(aftersales.getAdminAgreement());
        }

        // 5. 查询订单明细
        List<OrderItemVo> orderItems = orderItemService.listOrderItemsByOrderId(orderId);
        orderVo.setOrderitems(orderItems);

        // 6. 计算总数量
        int totalQuantity = orderItems.stream()
                .mapToInt(OrderItemVo::getQuantity)
                .sum();
        orderVo.setQuantity(totalQuantity);

        return orderVo;
    }

    //获取用户订单列表 根据用户ID
    @Override
    public List<OrderVo> getOrderVoByUserId(Integer userId) {
        // 1. 查询用户的所有订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, userId)
                .orderByDesc(Orders::getCreateTime); // 按创建时间倒序排列
        List<Orders> orders = list(queryWrapper);

        // 2. 若没有订单，直接返回空列表
        if (orders.isEmpty()) {
            return Collections.emptyList();
        }

        // 3. 处理每个订单，设置售后理由（如果有）
        return orders.stream()
                .map(order -> {
                    OrderVo orderVo = getOrderDetail(order.getOrderId());
                    if (orderVo != null && order.getOrderStatus() == 6) {
                        // 查询售后表获取售后理由
                        Aftersales aftersales = aftersalesMapper.selectOne(
                                new LambdaQueryWrapper<Aftersales>()
                                        .eq(Aftersales::getOrderId, order.getOrderId())
                                        .eq(Aftersales::getAdminAgreement, 0)
                        );
                        if (aftersales != null) {
                            orderVo.setReason(aftersales.getReason()); // 设置售后理由
                        }
                    }
                    return orderVo;
                })
                .filter(Objects::nonNull) // 过滤掉null值
                .collect(Collectors.toList());
    }

    //获取订单分页信息
    @Override
    public IPage<OrderVo> getOrderVoPage(Page<OrderVo> page, String keyword, Integer status) {
        // 构建查询条件
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        // 添加状态筛选条件
        if (status != null) {
            queryWrapper.eq(Orders::getOrderStatus, status);
        }

        // 添加关键词搜索
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(wrapper ->
                    wrapper.like(Orders::getOrderId, keyword)

            );
        }


        // 按创建时间倒序排列
        queryWrapper.orderByDesc(Orders::getCreateTime);

        // 创建Orders实体的分页对象
        Page<Orders> ordersPage = new Page<>(page.getCurrent(), page.getSize());

        // 执行分页查询（使用正确的Service方法）
        IPage<Orders> orderPage = page(ordersPage, queryWrapper);

        // 创建结果页面对象
        Page<OrderVo> resultPage = new Page<>(
                orderPage.getCurrent(),
                orderPage.getSize(),
                orderPage.getTotal()
        );

        // 转换订单实体为VO并填充详情
        List<OrderVo> orderVoList = orderPage.getRecords().stream()
                .map(order -> {
                    // 确保order.getId()返回订单ID
                    return getOrderDetail(order.getOrderId());
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 设置结果页面数据
        resultPage.setRecords(orderVoList);
        System.out.println(resultPage.getRecords());
        return resultPage;
    }

    // 获取用户订单列表 根据用户ID
    @Override
    public Result<List<Orders>> getOrderById(Integer userId) {

        //获取
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<Orders>()
                .select("order_id", "total_amount", "order_status", "pay_method", "create_time", "update_time")
                .eq("user_id", userId);


        List<Orders> orderList = orderMapper.selectList(queryWrapper);

        if(orderList==null){
            return Result.error("订单为空");
        }

        //根据订单id查找订单明细
        for(Orders order:orderList ){
            QueryWrapper<OrderItem> wrapper = new QueryWrapper<OrderItem>()
                    .eq("order_id",order.getOrderId());
            List<OrderItem> orderitems = orderItemMapper.selectList(wrapper);
            List<OrderItemVo> orderitemVOs = BeanUtil.copyToList(orderitems, OrderItemVo.class);
            order.setOrderitems(orderitemVOs);
        }
        log.info("用户的订单信息为：{}",orderList);
        return Result.success(orderList);

    }

    //生成订单号
    private String generateOrderId() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timestamp = LocalDateTime.now().format(formatter);
        String random = String.format("%04d", new Random().nextInt(10000));
        return timestamp + random;
    }


    //计算订单总金额
    private BigDecimal calculateTotalAmount(List<Cart> cartItems) {
        BigDecimal total = BigDecimal.ZERO;
        for (Cart cartItem : cartItems) {
            Book book = bookService.getById(cartItem.getBookId());
            total = total.add(book.getPrice().multiply(new BigDecimal(cartItem.getQuantity())));
        }
        return total;
    }

    //修改订单地址
    @Override
    public Result UpdateOrderAddress(OrderDTO orderDTO) {
        //订单号
        String orderId = orderDTO.getOrderId();
        //新地址id
        Integer newAddressId = orderDTO.getAddressId();

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");

        // 1. 验证订单是否存在且属于当前用户
        Orders order = getOne(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getOrderId, orderId)
                .eq(Orders::getUserId, userId));

        if (order == null) {
            return Result.error("订单不存在或无权限修改");
        }

        // 2. 验证订单状态是否允许修改地址（例如：未支付或未发货）
        if (!OrderStatus.PENDING_PAYMENT.getCode().equals(order.getOrderStatus())&&
                !OrderStatus.PENDING_SHIPMENT.getCode().equals(order.getOrderStatus())) {
            return Result.error("订单状态不允许修改地址");
        }

        // 3. 验证新地址是否存在且属于当前用户
        Address newAddress = addressService.getByAddressIdUserId(newAddressId, userId);

        if (newAddress == null) {
            return Result.error("新地址不存在或无权限使用");
        }

        // 4. 更新订单地址
        order.setAddressId(newAddressId);
        order.setUpdateTime(LocalDateTime.now());
        boolean success = updateById(order);

        if (!success) {
            return Result.error("地址修改失败");
        }
        return Result.success("地址修改成功");

    }

    //修改订单状态
    public Result UpdateOrderStatus(String orderId,Integer status) {
        System.out.println("修改订单状态"+orderId);
        //根据订单id查找原来的订单
        Orders orders = orderMapper.selectByOrderId(orderId);

        System.out.println("是否获取得到订单"+orders);

        if(orders==null){
            return Result.error("订单不存在");
        }

        //取消恢复库存
        if(status==5){
            List<OrderItem> orderItems = orderItemMapper.selectList(new QueryWrapper<OrderItem>().eq("order_id",orderId));
            for (OrderItem orderItem : orderItems) {
                Book book=bookMapper.selectById(orderItem.getBookId());
                bookService.increaseStock(book.getBookId(),orderItem.getQuantity());
            }
        }

        orders.setOrderStatus(status);
        orders.setUpdateTime(LocalDateTime.now());

        orderMapper.updateById(orders);
        return Result.success("修改订单成功！");
    }

    //删除订单根据订单号
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteOrderById(String orderId) {
        // 1. 查询订单是否存在
        Orders order = getById(orderId);
        if (order == null) {
            return Result.error("订单不存在");
        }

        // 2. 校验订单状态（只允许删除已完成或已取消或已售后完成的订单）
        if (!OrderStatus.COMPLETED.getCode().equals(order.getOrderStatus())&&
        !OrderStatus.CANCELED.getCode().equals(order.getOrderStatus())&&
                !OrderStatus.AFTER_SALES_COMPLETED.getCode().equals(order.getOrderStatus())) {
            return Result.error("订单状态不允许删除");
        }

        // 3. 删除关联的订单项
        LambdaQueryWrapper<OrderItem> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.eq(OrderItem::getOrderId, orderId);
        int deleteCount = orderItemMapper.delete(itemQueryWrapper);


        if (deleteCount <= 0) {
            return Result.error("删除订单项失败");
        }

        // 4. 删除订单
        boolean orderDeleteResult = removeById(orderId);

        if (!orderDeleteResult) {
            return Result.error("删除订单失败");
        }

        return Result.success("订单删除成功");
    }

    //批量删除订单
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result batchDeleteOrders(List<String> orderIds) {
        // 1. 验证订单列表是否为空
        if (orderIds == null || orderIds.isEmpty()) {
            return Result.error("订单ID列表不能为空");
        }

        // 2. 过滤重复ID（可选）
        orderIds = new ArrayList<>(new HashSet<>(orderIds));

        // 3. 查询所有存在的订单
        List<Orders> orders = list(
                new LambdaQueryWrapper<Orders>().in(Orders::getOrderId, orderIds)
        );

        // 4. 按状态分组订单ID
        Map<String, String> resultMap = new LinkedHashMap<>(); // 保持原始顺序

        // 4.1 处理不存在的订单
        Set<String> existingOrderIds = orders.stream()
                .map(Orders::getOrderId)
                .collect(Collectors.toSet());

        for (String id : orderIds) {
            if (!existingOrderIds.contains(id)) {
                resultMap.put(id, "订单不存在");
            }
        }

        // 4.2 处理状态不允许的订单
        List<String> validOrderIds = new ArrayList<>();
        for (Orders order : orders) {
            if (!OrderStatus.PENDING_PAYMENT.getCode().equals(order.getOrderStatus()) &&
                    !OrderStatus.CANCELED.getCode().equals(order.getOrderStatus())) {
                resultMap.put(order.getOrderId(), "状态不允许删除");
            } else {
                validOrderIds.add(order.getOrderId());
            }
        }

        // 5. 如果没有可删除的订单，直接返回
        if (validOrderIds.isEmpty()) {
            return Result.success("没有可删除的订单", resultMap);
        }

        // 6. 删除关联的订单项
        LambdaQueryWrapper<OrderItem> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.in(OrderItem::getOrderId, validOrderIds);
        orderItemMapper.delete(itemQueryWrapper);

        // 7. 删除订单
        removeByIds(validOrderIds);

        // 8. 标记成功的订单
        for (String id : validOrderIds) {
            resultMap.put(id, "删除成功");
        }

        return Result.success("批量删除完成", resultMap);
    }

    //获取售后结果
    @Override
    public Result getretuResult(String orderId) {
        QueryWrapper<Aftersales> wrapper = new QueryWrapper<Aftersales>()
                .eq(orderId!=null,"order_id",orderId);
        Aftersales aftersales = aftersalesMapper.selectOne(wrapper);

        if(aftersales==null){
            return Result.error("售后情况为空");
        }
        return Result.success(aftersales);
    }


    //处理售后
    @Override
    public Result UpdateRetResult(Aftersales aftersales) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<Orders>()
                .eq(aftersales.getOrderId()!=null,"order_id",aftersales.getOrderId());
        Orders orders = orderMapper.selectOne(wrapper);

        if(orders==null){
            Result.error("找不到用户订单");
        }
        //根据售后结果更新订单状态
        if(aftersales.getAdminAgreement()==1){
            //同意退款

            orders.setOrderStatus(7); //已售后完成

            //获取订单项 根据订单ID
            List<OrderItem> orderItems = orderItemMapper.selectList(new QueryWrapper<OrderItem>().eq("order_id",aftersales.getOrderId()));

            for (OrderItem orderItem : orderItems) {
                Book book=bookMapper.selectById(orderItem.getBookId());

                //恢复库存
                bookService.increaseStock(book.getBookId(),orderItem.getQuantity());
            }

            aftersales.setUpdateTime(LocalDateTime.now());

        }else{

            //拒绝退款 那订单状态还是售后完成
            orders.setOrderStatus(7);
            //给出拒绝售后理由
            aftersales.setAdminReason(aftersales.getAdminReason());
            aftersales.setUpdateTime(LocalDateTime.now());
        }
        //修改订单状态
        orderMapper.updateById(orders);

        aftersalesMapper.updateById(aftersales);
        return Result.success("售后成功");
    }

    //创建立即购买订单
    @Override
    public Result createOrderBuynow(Integer userId,OrderBuyNowDto orderBuyNowDto) {
        // 1. 参数校验
        if (orderBuyNowDto.getBookId() == null || orderBuyNowDto.getQuantity() == null
                 || orderBuyNowDto.getPayMethod() == null) {
            return Result.error("订单参数不完整");
        }

        if(orderBuyNowDto.getAddressId() == null){
            return Result.error("请选择收货地址");
        }

        // 2. 校验商品是否存在
        Book book = bookService.getById(orderBuyNowDto.getBookId());
        // 检查每本商品是否下架
        if (book == null || book.getStatus() == 0) { // 假设0表示下架状态
            return Result.error( "商品已下架");
        }


        // 3. 校验库存
        if (book.getStock() < orderBuyNowDto.getQuantity()) {
            return Result.error("库存不足");
        }

        // 4. 校验地址是否存在且属于当前用户
        Address address = addressService.getById(orderBuyNowDto.getAddressId());
        if (address == null || !address.getUserId().equals(userId)) {
            return Result.error("收货地址不存在或无权限");
        }

        // 5. 生成订单号
        String orderId = generateOrderId();

        // 6. 创建订单主表记录
        Orders order = new Orders();
        order.setOrderId(orderId);
        order.setUserId(userId);
        order.setAddressId(orderBuyNowDto.getAddressId());
        order.setTotalAmount(book.getPrice().multiply(new BigDecimal(orderBuyNowDto.getQuantity())));
        order.setOrderStatus(orderBuyNowDto.getOrderStatus()); // 是否支付
        order.setPayMethod(orderBuyNowDto.getPayMethod());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        save(order);

        // 7. 创建订单商品记录
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(orderId);
        orderItem.setBookId(book.getBookId());
        orderItem.setBooktitle(book.getTitle());
        orderItem.setBookcover(book.getCoverUrl());
        orderItem.setPrice(book.getPrice());
        orderItem.setQuantity(orderBuyNowDto.getQuantity());

        orderItemMapper.insert(orderItem);


        return Result.success(orderId);
    }

    //订单收货 用户端
    @Override
    public boolean receiptOrder(String orderId) {

        Orders order = orderMapper.selectById(orderId);
        if(order==null){
            return false;
        }
        order.setOrderStatus(4);
        return updateById(order);
    }


}
